package cn.tedu.dao;

import cn.tedu.entity.TAddress;
import cn.tedu.entity.TOrder;
import cn.tedu.entity.TOrderItem;
import cn.tedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * (TOrder)表数据库访问层
 *
 * @author makejava
 * @since 2021-12-23 22:02:29
 */
public class TOrderDao {
    public TOrder createOrder(TAddress address, TOrder order, List<TOrderItem> orderItemList) throws SQLException {
        Connection connection = DBUtils.getConnection();
        // 关闭自动提交事务
        connection.setAutoCommit(false);
        // 插入地址
        String sql = "INSERT INTO t_address (user_id,receive_name,full_address,postal_code,phone,mobile) VALUES	(?,?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, address.getUserId());
        statement.setString(2, address.getReceiveName());
        statement.setString(3, address.getFullAddress());
        statement.setString(4, address.getPostalCode());
        statement.setString(5, address.getPhone());
        statement.setString(6, address.getMobile());
        statement.executeUpdate();

        // 插入订单主表
        String sql1 = "INSERT INTO t_order (user_id, order_time, order_desc, total_price) VALUES (?,?,?,?)";
        PreparedStatement statement2 = connection.prepareStatement(sql1, PreparedStatement.RETURN_GENERATED_KEYS);
        statement2.setInt(1, order.getUserId());
        statement2.setString(2, order.getOrderTime());
        statement2.setString(3, order.getOrderDesc());
        statement2.setDouble(4, order.getTotalPrice());
        statement2.executeUpdate();

        ResultSet resultSet = statement2.getGeneratedKeys();
        int orderId = 0;
        if (resultSet.next()) {
            orderId = resultSet.getInt(1);
        }
        order.setId(orderId);

        // 插入订单子表
        // 拼接sql语句
        // 循环插入
        String sql2 = "INSERT INTO t_order_item(order_id, book_id, book_name, dang_price, book_num,amount) VALUES (?,?,?,?,?,?)";
        PreparedStatement statement3 = connection.prepareStatement(sql2);
        for (TOrderItem orderItem : orderItemList) {
            statement3.setInt(1, orderId);
            statement3.setInt(2, orderItem.getBookId());
            statement3.setString(3, orderItem.getBookName());
            statement3.setDouble(4, orderItem.getDangPrice());
            statement3.setInt(5, orderItem.getBookNum());
            statement3.setDouble(6, orderItem.getAmount());
            statement3.executeUpdate();
        }

        connection.commit();

        // 关闭资源
        statement3.close();
        statement2.close();
        statement.close();
        connection.close();

        return order;
    }

}

